<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\common\Frontend;
use app\common\library\Email;
use general\Random;
use think\facade\Validate;
use think\Request;
use PHPMailer\PHPMailer\Exception as PHPMailerException;

class Ems extends Frontend
{
    protected array $noNeedLogin = ['send'];

    public function initialize(): void
    {
        parent::initialize();
    }


    //邮箱发送
    public function seed()
    {
        $params = $this->request->post(['email']);
        $mail   = new Email();
        if (!$mail->configured) {
            $this->error('邮件发送服务不可用，请联系网站管理员进行配置~');
        }
        $validate = Validate::rule([
            'email'       => 'require|email',
        ])->message([
            'email'       => 'email format error'
        ]);
        if (!$validate->check($params)) {
            $this->error(($validate->getError()));
        }
        //  // 检查邮箱
        // $userInfo = User::where('email', $params['email'])->find();
        // 生成一个验证码
        $code    = Random::uuid();
        $subject = get_sys_config('site_name');
        // 图片附件, 必须是本地资源, 路径基于当前所在的文件路径
        $picArr = array(
            'avatar'    =>  "static/images/avatar.png" //附件
        );
        // 嵌入附件
        foreach ($picArr as $k => $v) {
            $mail->AddEmbeddedImage($v, $k); // 注意留意这个$k, 下面在img需要用到
        }
        $body    = "您的验证码是：' $code ',十分钟内有效~<p><a href='xx'><img src='static/images/avatar.png'></a>&nbsp;</p>";
        try {
            $mail->isSMTP();
            $mail->addAddress($params['email']);
            $mail->isHTML(true);
            $mail->setSubject($subject);
            $mail->Body = $body;
            $mail->send();
        } catch (PHPMailerException $e) {
            $this->error($mail->ErrorInfo);
        }

        $this->success(('Mail sent successfully~'));
    }
}
